//app.js
var Util = require('utils/util.js');
var qiniuUploader = require('utils/qiniuUploader.js');
App({
  onLaunch: function () {
    var this_ = this;
  },
  globalData: {
    userInfo: null,
    publicUrl:'https://test.tuihs.com/'
  },
  //post请求
  postRequest: function (data, callback){
    wx.request({
      url: 'https://test.tuihs.com/' + data.paraUrl,
      data: data.paraData,
      method: "POST",
      header: {
        "Content-Type": "application/json",
        'appid': wx.getAccountInfoSync().miniProgram.appId,
        "CmwealAccessToken": wx.getStorageSync('access_token')
      },
      success(res) {
        if (res.data.status == 401){
          wx.showToast({
            title: '请先登录',
            icon: 'success',
            image: '/images/shibai.png',
            duration: 2000
          })
          setTimeout(function () {
            wx.reLaunch({
              url: "../login/login"
            })
          }, 2000)
          return;
        }
        callback(res)
      }
    })
  },
  //get请求
  getRequest: function (data, callback) {
    wx.request({
      url: 'https://test.tuihs.com/' + data.paraUrl,
      data: data.paraData,
      header: {
        'content-type': 'application/json', // 默认值
				'appid': wx.getAccountInfoSync().miniProgram.appId,
        "CmwealAccessToken": wx.getStorageSync('access_token')
      },
      success(res) {
        if (res.data.status == 401) {
          wx.showToast({
            title: '请先登录',
            icon: 'success',
            image: '/images/shibai.png',
            duration: 2000
          })
          setTimeout(function () {
            wx.reLaunch({
              url: "../login/login"
            })
          }, 2000)
          return;
        }
        callback(res)
      }
    })
  },
  // 根据指定id删除数组对象
  removeItem:function(arrObj, key){
    for(var i = 0; i<arrObj.length;i++){
      if (arrObj[i].id == key) {
        arrObj.splice(i, 1)
      }
    }
    return arrObj
  },
  // 根据指定id获取数组对象
  findItem: function (arrObj, key) {
    var result;
    for (var i = 0; i < arrObj.length; i++) {
      if (arrObj[i].id == key) {
        result = arrObj[i];
      }
    }
    return result
  },

  // 初始化七牛相关参数
  initQiniu:function() {
    var options = {
      region: 'SCN', // 华北区
      uptoken: wx.getStorageSync('uploadToken'),
      domain: wx.getStorageSync('domain'),
      shouldUseQiniuFileName: false
    };
    qiniuUploader.init(options);
  },
  //上传图片
  upImg: function (data, callback){
    var that = this;
    wx.chooseImage({
      count: data.count,
      success: function (res) {
        var filePath = res.tempFilePaths;
        wx.request({
          url: 'https://test.tuihs.com/image/upload-token',
          data: '',
          header: {
            'content-type': 'application/json', // 默认值
						'appid': wx.getAccountInfoSync().miniProgram.appId,
            "CmwealAccessToken": wx.getStorageSync('access_token')
          },
          success(ress) {
            var arrAllImg=[];
            for (var i = 0; i < filePath.length;i++){
              qiniuUploader.upload(filePath[i], (res) => {
                callback(res)
              }, (error) => {
              }, {
                  region: 'SCN',
                  uploadURL: 'https://up-z2.qbox.me',
                  uptoken: ress.data.body.uploadToken,
                  domain: ress.data.body.domain,
                  bucket: ''
                })
            }
          }
        })
      },
    })
  },
  //加密
  makeBaseAuth(user, password) {
    var tok = user + ':' + password;
    var hash = this.base64_encode(tok);
    return 'Basic ' + hash;
  },
  base64_encode(str) { // 编码，配合encodeURIComponent使用
    var c1, c2, c3;
    var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var i = 0, len = str.length, strin = '';
    while(i <len) {
      c1 = str.charCodeAt(i++) & 0xff;
      if (i == len) {
        strin += base64EncodeChars.charAt(c1 >> 2);
        strin += base64EncodeChars.charAt((c1 & 0x3) << 4);
        strin += "==";
        break;
      }
      c2 = str.charCodeAt(i++);
      if (i == len) {
        strin += base64EncodeChars.charAt(c1 >> 2);
        strin += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
        strin += base64EncodeChars.charAt((c2 & 0xF) << 2);
        strin += "=";
        break;
      }
      c3 = str.charCodeAt(i++);
      strin += base64EncodeChars.charAt(c1 >> 2);
      strin += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
      strin += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
      strin += base64EncodeChars.charAt(c3 & 0x3F)
    }
    return strin
  },
  getPermission: function (obj) {
    wx.getLocation({
      success: function (res) {
      },
      fail: function () {
        wx.getSetting({
          success: function (res) {
            var statu = res.authSetting;
            if (!statu['scope.userLocation']) {
              wx.showModal({
                title: '是否授权当前位置',
                content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
                success: function (tip) {
                  if (tip.confirm) {
                    wx.openSetting({
                      success: function (data) {
                        if (data.authSetting["scope.userLocation"] === true) {
                          wx.showToast({
                            title: '授权成功',
                            icon: 'success',
                            duration: 1000
                          })
                        } else {
                          wx.showToast({
                            title: '授权失败',
                            icon: 'success',
                            duration: 1000
                          })
                        }
                      }
                    })
                  }
                }
              })
            }
          },
          fail: function (res) {
            wx.showToast({
              title: '调用授权窗口失败',
              icon: 'success',
              duration: 1000
            })
          }
        })
      }
    })
  },
  dianzan: function (e) {
    var that = this;
    var data = {
      paraUrl: 'interaction/create',
      paraData: {
        "type": "support",
        "interactionTarget": "group",
        "target": {
          "id": e.currentTarget.dataset.type.id,
          "code": e.currentTarget.dataset.type.code,
          "name": e.currentTarget.dataset.type.name
        }
      }
    }
  }
})